package com.sc.nft.consume;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.sc.nft.entity.UserEcologyHatchRecords;
import com.sc.nft.enums.MessageTopic;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalException;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.UserPredictEcologyHatchRewardsRecordsService;
import com.sc.nft.sup.ErrorCode;
import com.sc.nft.util.WeChatUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author：LiGen
 * @Package：com.sc.nft.consume
 * @Project：sc_metago
 * @name：PeriodicRewardInitializationConsumer
 * @Date：2024/8/9 14:04
 * @Filename：PeriodicRewardInitializationConsumer
 */
@RocketMQMessageListener(topic = MessageTopic.PERIODIC_REWARD_INITIALIZATION+"${spring.profiles.active}",consumerGroup =  MessageTopic.PERIODIC_REWARD_INITIALIZATION+"${spring.profiles.active}")
@Component
@Slf4j
@RequiredArgsConstructor
public class PeriodicRewardInitializationConsumer implements RocketMQListener<Long> {

    private final Redisson redisson;
    private final UserPredictEcologyHatchRewardsRecordsService userPredictEcologyHatchRewardsRecordsService;

    @Override
    public void onMessage(Long userEcologyHatchRecordId) {
        log.info("熔炼后-周期预计奖励处理锁 记录id：{},处理开始",userEcologyHatchRecordId);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Assert.notNull(userEcologyHatchRecordId,"熔炼后-周期预计奖励处理锁 记录id为空");

        RLock lock = redisson.getLock(RedisKeyEnum.PERIODIC_REWARD_INITIALIZATION.getKey()+ userEcologyHatchRecordId);

        try {
            boolean res = lock.tryLock(3, TimeUnit.SECONDS);
            if (!res){
                throw new GlobalException("该熔炼记录预计奖励在处理");
            }
            userPredictEcologyHatchRewardsRecordsService.save(userEcologyHatchRecordId);
        } catch (Exception e) {
            WeChatUtil.sendLiGenWeChatMessage(StrUtil.format("熔炼-周期预计奖励处理失败 记录id：{},异常:{}", userEcologyHatchRecordId, e.getMessage()));
            log.error("熔炼-周期预计奖励处理失败 记录id：{},异常:{}", userEcologyHatchRecordId, e.getMessage());
        }finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
